import request from '@/utils/request'
import { onMounted, reactive, ref } from 'vue'
import useFetch from './useFetch'

export type FetchOptions = {
  method?: 'POST' | 'GET'

  manual?: boolean
  defaultParams?: Record<string, any>
  headers?: Record<string, any>

  onAfter?: (res: any) => any
  onSuccess?: (res: any, params: any) => any
}

export default <TData>(url: string, options: FetchOptions) => {
  const list = ref([])
  const isAll = ref(false)
  const pages = reactive({ page: 1, pageSize: 30 })

  const res = useFetch(url, {
    ...options,
    defaultParams: {
      ...pages,
      ...options.defaultParams,
    },
    onSuccess(res) {
      if (pages.page === 1) {
        list.value.length = 0
      }
      list.value = list.value.concat(res.list)
      isAll.value = list.value.length >= (res.total || list.value.length)
    },
  })

  const run = (params) =>
    res.run({
      ...pages,
      ...params,
    })

  const nextPage = (params) => {
    pages.page++
    run(params)
  }

  const resetToFirst = (params) => {
    pages.page = 1
    run(params)
  }

  return {
    ...res,
    pages,
    list,
    isAll,
    run,
    nextPage,
    resetToFirst
  }
}
